<?php

namespace App\Services;

use App\Models\Order;

/**
 * 支付服务
 * Class PayService
 * @package App\Services
 */
class PayService extends BaseService
{
    /**
     * 支付入口
     * @param $data
     * @return array
     * @throws \Throwable
     */
    public function pay($data)
    {
        $info = [];//   返回参数
        //先判断一下 支付金额小于等于0的情况
        if($data['pay_price'] <= 0){
            $payPriceStatus = OrderService::jsPayPrice($data['orderId'], $data['uid'], $data['payAttach']);
            $info = [
                'status' => 'SUCCESS',
                'pay_type' => 'ZERO',
                'result' => ['data' => $payPriceStatus, 'orderId' => $data['orderId']],
            ];
            return $info;
        }

        //支付宝app支付
        if($data['payType'] == 'aliapp'){

//            $payapi = new AliyunService();
//            $res = $payapi->cerateAlipay($data['orderId'], $data['body'], $data['payAttach'],$data['isGroup']);
//
//            $info = [
//                'status' => 'SUCCESS',
//                'pay_type' => 'aliapp_pay',
//                'result' => ['data' => $res, 'orderId' => $data['orderId']],
//            ];
//            return $info;
            $info['status'] = 'PAY_ERROR';
            $info['errorCode'] = -1;
            $info['message'] = '暂不支持支付宝';
            return  $info;

        //微信app支付
        }elseif($data['payType'] ==  'wxapp'){
            $res = WechatService::appPay($data['orderId'], $data['body'], $data['payAttach']); //创建订单wxapp
            $info = [
                'status' => 'SUCCESS',
                'pay_type' => 'wxapp_pay',
                'result' => ['data' => $res, 'orderId' => $data['orderId']],
            ];
            return $info;

            //小程序支付
        }elseif($data['payType'] ==  'weixin'){
            $jsConfig = WechatService::jsPay($data['orderId'], $data['body'], $data['payAttach']); //创建订单jspay
            $info = [
                'status' => 'WECHAT_PAY',
                'pay_type' => 'weixin_pay',
                'result' => ['data' => $jsConfig, 'orderId' => $data['orderId']],
            ];
            return $info;

        }elseif ($data['payType'] ==  'yue' && $data['payAttach'] != 'recharge_balance'){

            $orderInfo = Order::whereOrderId($data['orderId'])->first();
            $ret = OrderService::yuePay($orderInfo, $data['payAttach']);
            $info = [
                'status' => 'SUCCESS',
                'pay_type' => 'yue',
                'result' => ['data' => $ret, 'orderId' => $data['orderId']],
            ];

            if(isset($ret['errno'])){
                $info['errorCode'] = -1;
                $info['status'] = 'error';
                $info['message'] = $ret['message'];
            }

            return $info;


        }else{
            $info['status'] = 'PAY_ERROR';
            $info['errorCode'] = -1;
            $info['message'] = '支付类型错误';
            return  $info;
        }
    }
}